package cn.itsource.basic.util;

import cn.itsource.basic.domain.LoginData;
import cn.itsource.basic.jwt.JwtUtils;
import cn.itsource.basic.jwt.Payload;
import cn.itsource.basic.jwt.RsaUtils;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Logininfo;
import cn.itsource.org.domain.User;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.mapper.UserMapper;
import com.sun.net.httpserver.HttpContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;


public class CurrentUserUtil {

    public static ConfigurableApplicationContext applicationContext;

    //定义一个获取已经实例化bean的方法
    public static <T> T getBean(Class<T> c){
        return applicationContext.getBean(c);
    }

    public static Long getCurrentUtil(HttpServletRequest request) throws Exception {
        //从请求头中获取token
        String token = request.getHeader("U-TOKEN");
        if(StringUtils.isNotEmpty(token)){
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            Payload<LoginData> info = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
            Logininfo logininfo = info.getUserInfo().getLogininfo();
            //判断当前用户是管理员还是主站用户
            if(logininfo.getType() == 1){
                //用户
                UserMapper userMapper = getBean(UserMapper.class);
                User user = userMapper.loadByLogininfoId(logininfo.getId());
                return user.getId();
            }else{
                //管理员
                EmployeeMapper employeeMapper = getBean(EmployeeMapper.class);
                Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
                return employee.getId();
            }
        }
        return null;
    }
}
